#include "game_map.h"

USING_NS_CC;
using std::vector;

GameMap* GameMap::create(const char *file)
{
    auto pRet = new GameMap();
    if ( pRet && pRet->init(file) )
    {
        pRet->autorelease();
        return pRet;
    }
    CC_SAFE_DELETE(pRet);
    return nullptr;
}

bool GameMap::init(const char *file)
{
    if ( !Node::init() )
        return false;

    _tiledMap = TMXTiledMap::create(file);
    
    auto meta = _tiledMap->getLayer("meta");
    meta->setVisible(false);

    _mapWidth = _tiledMap->getMapSize().width;
    _mapHeight = _tiledMap->getMapSize().height;
    _cellWidth = _tiledMap->getTileSize().width;
    _cellHeight = _tiledMap->getTileSize().height;

    for ( int row = 0; row < _mapHeight; ++row )
    {
        for ( int col = 0; col < _mapWidth; ++col )
        {
            Point cellCoord(col, row);
            int GID = meta->tileGIDAt(cellCoord);
            if ( GID )
            {
                ValueMap properties = _tiledMap->propertiesForGID(GID).asValueMap();
                CellData cell;
                cell.col = col;
                cell.row = row;
                cell.alpha = properties["alpha"].asBool();
                cell.obstacle = properties["obstacle"].asBool();
                _cellDatas.push_back(cell);
            }
        }
    }
    _astar.makeGrid(this);

    addChild(_tiledMap);
}
    
void GameMap::setOffset(float x, float y)
{
    _tiledMap->setPosition(x, y);
}

const CellData& GameMap::getCellData(int col, int row) const
{
    int index = row * _mapWidth + col;
    return _cellDatas[index];
}

void GameMap::getPath(vector<cocos2d::Point> &result, int srcX, int srcY, int descX, int descY)
{
	_astar.find(result, srcX, srcY, descX, descY);
}